import React, { useState, useEffect, useRef } from 'react';
import { Modal, Tree, Form, Select, DatePicker, Space, Button, Spin, message, Pagination, Input } from 'antd';
import type { DataNode } from 'antd/es/tree';
import DraggableTable from '@/components/DraggableTable';
import request from '@/utils/request';
import './AddDataModal.css';

const { RangePicker } = DatePicker;

interface AddDataModalProps {
  open: boolean;
  onCancel: () => void;
  onOk: (selectedData: any[]) => void;
  datasetId: number;
  treeUuid: string;
}

const AddDataModal: React.FC<AddDataModalProps> = ({ open, onCancel, onOk, datasetId, treeUuid }) => {
  const [treeSelected, setTreeSelected] = useState<string[]>([]);
  const [dataKey, setDataKey] = useState<string>('');
  const [form] = Form.useForm();
  const [current, setCurrent] = useState(1);
  const [pageSize, setPageSize] = useState(20);
  const [dataLevels, setDataLevels] = useState<Array<{ key: string; label: string; count: number; size: string }>>([]);
  const [versionOptions, setVersionOptions] = useState<string[]>([]);
  const [stationOptions, setStationOptions] = useState<string[]>([]);
  const [workModeOptions, setWorkModeOptions] = useState<string[]>([]);
  const [dataLevel, setDataLevel] = useState('');
  const [tableData, setTableData] = useState<any[]>([]);
  const [treeDataState, setTreeDataState] = useState<DataNode[]>([]);
  const [treeLoading, setTreeLoading] = useState(false);
  const [tableLoading, setTableLoading] = useState(false);
  const [total, setTotal] = useState(0);
  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [sortState, setSortState] = useState<{
    field: string | null;
    order: 'ascend' | 'descend' | null;
  }>({
    field: null,
    order: null
  });
  const [filterParams, setFilterParams] = useState<{
    work_mode?: string;
    version_num?: string;
    station?: string;
    track_num_turns__gte?: string;
    track_num_turns__lte?: string;
    collection_time__gte?: string;
    collection_time__lte?: string;
    archive_time__gte?: string;
    archive_time__lte?: string;
  }>({});
  const tableContainerRef = useRef<HTMLDivElement>(null);
  const [tableScrollY, setTableScrollY] = useState<number>(0);

  const defaultColumns = [
    {
      title: '文件名',
      dataIndex: 'file_name',
      key: 'file_name',
      width: 300,
      ellipsis: { showTitle: false }
    },
    {
      title: '数据大小(MB)',
      dataIndex: 'data_size',
      key: 'data_size',
      width: 140,
      sorter: true,
      sortDirections: ['ascend', 'descend'] as const,
      render: (value: number) => (value / 1024 / 1024).toFixed(2)
    },
    {
      title: '任务型号',
      dataIndex: 'task_type',
      key: 'task_type',
      width: 100,
      sorter: true,
      sortDirections: ['ascend', 'descend'] as const
    },
    {
      title: '载荷',
      dataIndex: 'dm_zhname',
      key: 'dm_zhname',
      width: 100,
      sorter: true,
      sortDirections: ['ascend', 'descend'] as const
    },
    {
      title: '数据级别',
      dataIndex: 'data_level',
      key: 'data_level',
      width: 100,
      sorter: true,
      sortDirections: ['ascend', 'descend'] as const
    },
    {
      title: '轨道圈数',
      dataIndex: 'track_num_turns',
      key: 'track_num_turns',
      width: 100,
      sorter: true,
      sortDirections: ['ascend', 'descend'] as const
    },
    {
      title: '采集开始时间',
      dataIndex: 'collection_time_start',
      key: 'collection_time_start',
      width: 180,
      sorter: true,
      sortDirections: ['ascend', 'descend'] as const
    },
    {
      title: '采集结束时间',
      dataIndex: 'collection_time_end',
      key: 'collection_time_end',
      width: 180,
      sorter: true,
      sortDirections: ['ascend', 'descend'] as const
    },
    {
      title: '归档时间',
      dataIndex: 'archive_time',
      key: 'archive_time',
      width: 180,
      sorter: true,
      sortDirections: ['ascend', 'descend'] as const
    }
  ];

  const [columns, setColumns] = useState(defaultColumns);

  // 计算表格滚动高度的函数
  const calculateTableScrollHeight = () => {
    if (tableContainerRef.current) {
      const containerHeight = tableContainerRef.current.clientHeight;
      const tableHeaderHeight = 42; // antd Table 的 header 高度

      const scrollHeight = containerHeight - tableHeaderHeight;
      setTableScrollY(scrollHeight);

      const body = tableContainerRef.current.querySelector('.ant-table-body');
      if (body) {
        (body as HTMLElement).style.height = Math.max(scrollHeight, 0) + 'px';
      }
    }
  };

  // 添加窗口大小变化的监听
  useEffect(() => {
    calculateTableScrollHeight();
    window.addEventListener('resize', calculateTableScrollHeight);

    return () => {
      window.removeEventListener('resize', calculateTableScrollHeight);
    };
  }, []);

  useEffect(() => {
    calculateTableScrollHeight();
  }, [dataLevels]);

  // 获取数据等级信息
  const fetchDataLevel = async () => {
    try {
      if (!dataKey) {
        return;
      }
      const response = await request.get('/Management/DataLevel', {
        params: { data_key: dataKey, ...filterParams }
      });

      if (response.status === 200) {
        const { data_level } = response.data.data;

        // 更新数据等级标签
        const newDataLevels = data_level.map((item: any) => ({
          key: item.level,
          label: item.level === '' ? '全部' : `${item.level}级`,
          count: item.count,
          size: `${(item.size / 1024 / 1024 / 1024).toFixed(2)}GB`
        }));
        setDataLevels(newDataLevels);
      }
    } catch (error: any) {
      message.error(error?.message || '获取数据等级信息失败');
    }
  };

  // 获取筛选选项
  const fetchFilterOptions = async () => {
    try {
      if (!dataKey) {
        return;
      }

      const response = await request.get('/Management/DataFilterOptions', {
        params: { data_key: dataKey, data_level: dataLevel }
      });

      if (response.status === 200) {
        const { work_modes, version_nums, station } = response.data.data;
        setWorkModeOptions(work_modes || []);
        setVersionOptions(version_nums || []);
        setStationOptions(station || []);
      }
    } catch (error: any) {
      message.error(error?.message || '获取筛选选项失败');
    }
  };

  // 获取数据列表
  const fetchTableData = async () => {
    setTableLoading(true);
    try {
      if (!dataKey) {
        return;
      }

      const queryParams = {
        data_key: dataKey,
        ...filterParams,
        data_level: dataLevel,
        ordering: sortState.field ? `${sortState.order === 'descend' ? '-' : ''}${sortState.field}` : undefined,
        page: current,
        page_size: pageSize
      };

      const response = await request.get('/Management/DataList', {
        params: queryParams
      });

      if (response.status === 200) {
        const { list, count, page } = response.data.data;

        // 更新表格数据
        const formattedData = list.map((item: any) => ({
          key: item.product_id,
          product_id: item.product_id,
          file_name: item.file_name,
          file_path: item.file_path,
          bk_pstate: item.bk_pstate,
          data_type: item.data_type,
          release_status: item.release_status,
          collection_time_start: item.collection_time_start,
          collection_time_end: item.collection_time_end,
          archive_time: item.archive_time,
          data_size: item.data_size,
          task_type: item.task_type,
          station: item.station,
          dm_zhname: item.dm_zhname,
          version_num: item.version_num,
          track_num_turns: item.track_num_turns,
          is_favorites: item.is_favorites
        }));

        setTableData(formattedData);
        setCurrent(page);
        setTotal(count);
      }
    } catch (error: any) {
      message.error(error?.message || '获取数据列表失败');
    } finally {
      setTableLoading(false);
    }
  };

  const fetchTreeData = async () => {
    setTreeLoading(true);
    try {
      const response = await request.get(`/Management/DirectoryTree`, {
        params: { data_type: 1 }
      });
      if (response.status === 200) {
        // Transform API data to match Tree component using recursive function
        const transformTreeData = (items: any[], level = 1): DataNode[] => {
          return items.map((item) => ({
            title: item.name,
            key: item.value,
            className: level === 1 ? 'level-1-node' : level === 2 ? 'level-2-node' : '',
            children: item.children ? transformTreeData(item.children, level + 1) : []
          }));
        };

        const newTreeData = transformTreeData(response.data.data);
        setTreeDataState(newTreeData);

        // 展开所有节点，唯独不展开第一层级的第一个节点以外的节点，但这些未展开的一级节点的子节点全部展开
        let expandedKeys: React.Key[] = [];
        if (newTreeData.length > 0) {
          // 第一个一级节点key加入expandedKeys
          expandedKeys.push(newTreeData[0].key);
          // 递归收集所有子节点key（不包括一级节点本身，除了第一个）
          const collectAllDescendantKeys = (nodes: DataNode[]): React.Key[] => {
            let keys: React.Key[] = [];
            nodes.forEach((node: DataNode) => {
              if (node.children && node.children.length > 0) {
                keys = keys.concat(node.children.map((child: DataNode) => child.key));
                keys = keys.concat(collectAllDescendantKeys(node.children));
              }
            });
            return keys;
          };
          // 第一个一级节点递归收集所有子孙节点key（包括多层）
          if (newTreeData[0].children && newTreeData[0].children.length > 0) {
            expandedKeys = expandedKeys.concat(collectAllDescendantKeys([newTreeData[0]]));
          }
          // 其他一级节点递归收集所有子孙节点key（不包括本身）
          for (let i = 1; i < newTreeData.length; i++) {
            const node = newTreeData[i];
            if (node?.children && node.children.length > 0) {
              expandedKeys = expandedKeys.concat(collectAllDescendantKeys([node]));
            }
          }
        }
        setExpandedKeys(expandedKeys);
      }
    } catch (error: any) {
      message.error(error?.message || '加载树形数据失败');
    } finally {
      setTreeLoading(false);
    }
  };

  useEffect(() => {
    fetchTreeData();
  }, []);

  useEffect(() => {
    if (dataKey) {
      fetchDataLevel();
      fetchFilterOptions();
      setFilterParams({});
      form.resetFields();
      setCurrent(1);
      setDataLevel('');
    }
  }, [dataKey]);

  useEffect(() => {
    if (dataKey) {
      fetchFilterOptions();
      setCurrent(1);
    }
  }, [dataLevel]);

  useEffect(() => {
    if (dataKey) {
      fetchTableData();
    }
  }, [current, pageSize, dataLevel, sortState, filterParams]);

  useEffect(() => {
    if (dataKey) {
      fetchDataLevel();
    }
  }, [filterParams]);

  // 监听 open 变化，open 为 true 时刷新数据
  useEffect(() => {
    if (open) {
      fetchTreeData();
      form.resetFields();
      setCurrent(1);
      setDataLevel('');
      setFilterParams({});
      setSelectedRowKeys([]);
    }
  }, [open]);

  // 检查节点是否可勾选（第一层级和第二层级不可选，第三层级及以下可选）
  const isNodeSelectable = (node: DataNode, treeData: DataNode[]): boolean => {
    // 检查节点是否在第一层级
    const isFirstLevel = treeData.some((firstLevelNode) => firstLevelNode.key === node.key);
    if (isFirstLevel) return false;

    // 检查节点是否在第二层级
    const isSecondLevel = treeData.some((firstLevelNode) =>
      firstLevelNode.children?.some((secondLevelNode) => secondLevelNode.key === node.key)
    );
    if (isSecondLevel) return false;

    // 第三层级及以下可选
    return true;
  };

  // 获取第一个可勾选的节点（第三层级）
  const getFirstSelectableNode = (nodes: DataNode[]): string | null => {
    // 遍历第一层级节点
    for (const firstLevelNode of nodes) {
      if (firstLevelNode.children) {
        // 遍历第二层级节点
        for (const secondLevelNode of firstLevelNode.children) {
          if (secondLevelNode.children && secondLevelNode.children.length > 0) {
            // 返回第一个第三层级节点
            return secondLevelNode.children[0].key as string;
          }
        }
      }
    }
    return null;
  };

  // 手风琴效果的onExpand
  const handleExpand = (keys: React.Key[], { expanded, node }: any) => {
    const isFirstLevel = treeDataState.some((firstLevelNode) => firstLevelNode.key === node.key);
    if (isFirstLevel) {
      // 只影响一级节点展开状态，子节点key保持不变
      const firstLevelKeys = treeDataState.map((n) => n.key);
      let newExpandedKeys;
      if (expanded) {
        // 展开当前一级节点，移除其它一级节点key，保留子节点key
        newExpandedKeys = [node.key, ...expandedKeys.filter((k) => !firstLevelKeys.includes(k) && k !== node.key)];
      } else {
        // 收起当前一级节点，只移除该key，保留其它key
        newExpandedKeys = expandedKeys.filter((k) => k !== node.key);
      }
      setExpandedKeys(newExpandedKeys);
    } else {
      // 下级节点展开/收起，正常处理
      setExpandedKeys(keys);
    }
  };

  // 监听树形数据变化，自动选择第一个可勾选节点
  useEffect(() => {
    if (treeDataState.length > 0) {
      const firstSelectableKey = getFirstSelectableNode(treeDataState);
      if (firstSelectableKey) {
        setTreeSelected([firstSelectableKey]);
        setDataKey(firstSelectableKey);
      }
    }
  }, [treeDataState]);

  // 行选择配置
  const rowSelection = {
    selectedRowKeys,
    columnWidth: 50,
    onChange: (keys: React.Key[]) => setSelectedRowKeys(keys)
  };

  // 筛选表单提交
  const onFinish = (values: any) => {
    // 处理时间范围
    if (values.collection_time_range) {
      values.collection_time__gte = values.collection_time_range[0]?.format('YYYY-MM-DD 00:00:00');
      values.collection_time__lte = values.collection_time_range[1]?.format('YYYY-MM-DD 23:59:59');
      delete values.collection_time_range;
    }

    if (values.archive_time_range) {
      values.archive_time__gte = values.archive_time_range[0]?.format('YYYY-MM-DD 00:00:00');
      values.archive_time__lte = values.archive_time_range[1]?.format('YYYY-MM-DD 23:59:59');
      delete values.archive_time_range;
    }
    // 重置分页
    setCurrent(1);
    setFilterParams(values);
  };

  // 处理确认按钮点击
  const handleOk = async () => {
    const selectedData = tableData.filter((item) => selectedRowKeys.includes(item.key));
    try {
      const files = selectedData.map((item) => ({
        data_type: item.data_type || 'DmSpinfo', // 默认为 DmSpinfo
        product_id: item.product_id
      }));

      const response = await request('/PDS/DataSetTemplateDataCreate', {
        method: 'POST',
        data: {
          dataset_id: datasetId,
          tree_uuid: treeUuid,
          query_params: {
            ...filterParams,
            data_key: dataKey,
            data_level: dataLevel
          },
          files
        }
      });

      if (response.data.code === 200) {
        message.success('添加数据成功');
        onOk(selectedData);
      } else {
        message.error(response.data.msg || '添加数据失败');
      }
    } catch (error) {
      console.error('添加数据失败:', error);
      message.error(error instanceof Error ? error.message : '添加数据失败');
    }
  };

  // 处理全部添加
  const handleAddAll = async () => {
    try {
      const response = await request('/Management/DataSetCreateOrderListAll', {
        method: 'GET',
        params: {
          dataset_id: datasetId,
          tree_uuid: treeUuid,
          ...filterParams,
          data_key: dataKey,
          data_level: dataLevel
        }
      });

      if (response.data.code === 200) {
        message.success('全部添加数据成功');
        onOk(tableData);
      } else {
        message.error(response.data.msg || '全部添加数据失败');
      }
    } catch (error) {
      message.error(error instanceof Error ? error.message : '全部添加数据失败');
    }
  };

  return (
    <Modal
      title="添加数据"
      open={open}
      onCancel={onCancel}
      width={'90%'}
      styles={{ body: { height: 'calc(100vh - 200px)', overflow: 'hidden' } }}
      style={{ top: 50, bottom: 50 }}
      footer={null}>
      <div style={{ display: 'flex', gap: '16px', height: '100%' }}>
        {/* 左侧树形结构 */}
        <div
          className="add-data-modal-tree-container"
          style={{
            width: '300px',
            flexShrink: 0,
            background: '#fafafa',
            borderRadius: '3px',
            padding: '5px',
            overflow: 'auto'
          }}>
          <Spin spinning={treeLoading}>
            <Tree
              blockNode
              treeData={treeDataState}
              expandedKeys={expandedKeys}
              onExpand={handleExpand}
              selectedKeys={treeSelected}
              onSelect={(selectedKeys, info) => {
                if (selectedKeys.length === 0) {
                  return;
                }
                const isSelectable = isNodeSelectable(info.node, treeDataState);
                if (isSelectable) {
                  setTreeSelected(selectedKeys.map(String));
                  setDataKey(selectedKeys[0] as string);
                } else {
                  // 不可选择的节点，用于展开/收起子节点
                  const nodeKey = info.node.key;
                  const isExpanded = expandedKeys.includes(nodeKey);
                  
                  if (isExpanded) {
                    // 如果节点已展开，则收起
                    setExpandedKeys(expandedKeys.filter(key => key !== nodeKey));
                  } else {
                    // 如果节点未展开，则展开
                    setExpandedKeys([...expandedKeys, nodeKey]);
                  }
                  
                  // 清空选择状态
                  setTreeSelected([]);
                }
              }}
              style={{ minHeight: 100 }}
            />
          </Spin>
        </div>

        {/* 右侧内容区 */}
        <div style={{ flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column' }}>
          {/* 筛选表单 */}
          <Form form={form} layout="inline" className="filter-form" onFinish={onFinish} labelCol={{ span: 6 }} wrapperCol={{ span: 18 }}>
            <Form.Item name="version_num" label="版本号" style={{ width: 320 }}>
              <Select allowClear placeholder="请选择版本号" style={{ width: '100%' }}>
                {versionOptions.map((option) => (
                  <Select.Option key={option} value={option}>
                    {option}
                  </Select.Option>
                ))}
              </Select>
            </Form.Item>

            <Form.Item name="work_mode" label="工作模式" style={{ width: 320 }}>
              <Select allowClear placeholder="请选择工作模式" style={{ width: '100%' }}>
                {workModeOptions.map((option) => (
                  <Select.Option key={option} value={option}>
                    {option}
                  </Select.Option>
                ))}
              </Select>
            </Form.Item>

            <Form.Item name="station" label="接收站" style={{ width: 320 }}>
              <Select allowClear placeholder="请选择接收站" style={{ width: '100%' }}>
                {stationOptions.map((option) => (
                  <Select.Option key={option} value={option}>
                    {option}
                  </Select.Option>
                ))}
              </Select>
            </Form.Item>

            <Form.Item label="采集时间" style={{ width: 320 }} name="collection_time_range">
              <RangePicker style={{ width: '100%' }} placeholder={['开始时间', '结束时间']} />
            </Form.Item>

            <Form.Item label="归档时间" style={{ width: 320 }} name="archive_time_range">
              <RangePicker style={{ width: '100%' }} placeholder={['开始时间', '结束时间']} />
            </Form.Item>

            <Form.Item 
              label="轨道圈数/探测周期编号" 
              style={{ 
                width: 320,
                '--ant-form-item-label-width': '160px'
              } as React.CSSProperties}
            >
              <Space style={{ width: '100%' }}>
                <Form.Item name="track_num_turns__gte" noStyle style={{ flex: 1 }}>
                  <Input type="number" placeholder="起始" style={{ width: '70px' }} min={0} />
                </Form.Item>
                <span style={{ color: '#999' }}>—</span>
                <Form.Item name="track_num_turns__lte" noStyle style={{ flex: 1 }}>
                  <Input type="number" placeholder="结束" style={{ width: '70px' }} min={0} />
                </Form.Item>
              </Space>
            </Form.Item>

            <Form.Item style={{ paddingLeft: 80, width: 320 }}>
              <Space>
                <Button type="primary" htmlType="submit">
                  筛选
                </Button>
                <Button htmlType="button" onClick={() => form.resetFields()}>
                  清除
                </Button>
              </Space>
            </Form.Item>
          </Form>

          {/* 数据等级标签 */}
          <div className="fixed-filter-tabs">
            {dataLevels.map((tab) => (
              <span
                key={tab.key}
                className={`filter-tab-item${dataLevel === tab.key ? ' active' : ''}`}
                onClick={() => setDataLevel(tab.key)}>
                {tab.label}({tab.count}/{tab.size})
              </span>
            ))}
          </div>

          {/* 数据表格 */}
          <div ref={tableContainerRef} style={{ flex: 1, overflow: 'hidden' }}>
            <DraggableTable
              rowSelection={rowSelection}
              columns={columns}
              dataSource={tableData}
              pagination={false}
              tableLayout="fixed"
              style={{ flex: 1 }}
              scroll={{
                y: tableScrollY,
                x: 'max-content'
              }}
              bordered
              size="small"
              loading={tableLoading}
              rowClassName={(_: any, index: number) => (index % 2 === 0 ? 'zebra-row-odd' : 'zebra-row-even')}
              onChange={(_: any, __: any, sorter: any) => {
                if (sorter.field) {
                  setSortState({
                    field: sorter.field,
                    order: sorter.order
                  });
                }
              }}
              onColumnsChange={(newColumns) => setColumns(newColumns)}
            />
          </div>

          {/* 分页 */}
          <div style={{ marginTop: 10, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <Space>
              <Button type="primary" onClick={handleOk} disabled={selectedRowKeys.length === 0}>
                添加数据
              </Button>
              <Button type="primary" onClick={handleAddAll} disabled={tableData.length === 0}>
                全部添加
              </Button>
            </Space>
            <Pagination
              current={current}
              pageSize={pageSize}
              total={total}
              showSizeChanger
              pageSizeOptions={['10', '20', '50']}
              onChange={(page, size) => {
                setCurrent(page);
                setPageSize(size!);
              }}
              showTotal={(total) => `共 ${total} 条`}
            />
          </div>
        </div>
      </div>
    </Modal>
  );
};

export default AddDataModal;
